'use strict';

const Controller = require('../lib/controller');

class HomeController extends Controller {
  async index() {
    // Redirect For Permalink URL ///////////////////////////
    if (this.ctx.request.query.id) {
      this.ctx.redirect('article.asp?id=' + this.ctx.request.query.id);
    }

    // Process Default Page /////////////////////////////////
    let strURLPrefix = '?';
    let sqlWHERE = ' WHERE 1=1';
    let arrKeywords = '';

    // Check view Mode
    let viewMode;
    if (this.ctx.request.query.mode == 'list') {
      this.ctx.session.viewMode = 1;
    } else if (this.ctx.request.query.mode == 'normal') {
      this.ctx.session.viewMode = 0;
    }
    if (this.ctx.session.viewMode != 0 && this.ctx.session.viewMode != 1) {
      viewMode = this.ctx.app.theCache.settings.defaultViewMode;
    } else {
      viewMode = this.ctx.session.viewMode;
    }

    // Check current page number
    if (this.ctx.request.query.page) {
      this.ctx.request.query.page = this.ctx.helper.checkInt(this.ctx.request.query.page);
      if (this.ctx.request.query.page <= 0) {
        this.ctx.request.query.page = 1;
      }
    } else {
      this.ctx.request.query.page = 1;
    }

    // Check if output selected content only
    if (this.ctx.request.query.selected == 'true') {
      sqlWHERE += ' AND log_selected=true';
      strURLPrefix += strURLPrefix == '?' ? '' : '&amp;';
      strURLPrefix += 'selected=true';
    }

    // Check category id
    if (this.ctx.request.query.cat) {
      this.ctx.request.query.cat = this.ctx.helper.checkInt(this.ctx.request.query.cat);
      if (this.ctx.request.query.cat > 0) {
        sqlWHERE += ' AND log_catID=' + this.ctx.request.query.cat;
        strURLPrefix += strURLPrefix == '?' ? '' : '&amp;';
        strURLPrefix += 'cat=' + this.ctx.request.query.cat;
      }
    }

    // Check user id
    if (this.ctx.request.query.user) {
      this.ctx.request.query.user = this.ctx.helper.checkInt(this.ctx.request.query.user);
      if (this.ctx.request.query.user > 0) {
        sqlWHERE += ' AND log_authorID=' + this.ctx.request.query.user;
        strURLPrefix += strURLPrefix == '?' ? '' : '&amp;';
        strURLPrefix += 'user=' + this.ctx.request.query.user;
      }
    }

    // Check if doing search
    if (this.ctx.request.query.q) {
      arrKeywords = this.ctx.request.query.q.split(' ');
      for (var i = 0; i < arrKeywords.length; i++) {
        if (this.ctx.helper.lengthW(arrKeywords[i]) > 2) {
          sqlWHERE += " AND (log_title LIKE '%" + this.ctx.helper.checkStr(arrKeywords[i]) + "%' OR log_content0 LIKE '%" + this.ctx.helper.checkStr(arrKeywords[i]) + "%' OR log_content1 LIKE '%" + this.ctx.helper.checkStr(arrKeywords[i]) + "%')";
        }
      }
      strURLPrefix += strURLPrefix == '?' ? '' : '&amp;';
      strURLPrefix += 'q=' + this.ctx.request.query.q;
    }

    // Check if has highlight keywords
    if (this.ctx.request.query.hl) {
      arrKeywords = this.ctx.request.query.hl.split(' ');
      strURLPrefix += strURLPrefix == '?' ? '' : '&amp;';
      strURLPrefix += 'hl=' + this.ctx.request.query.hl;
    }

    // Check date range
    let intYear;
    let intMonth;
    let intDay;
    if (this.ctx.request.query.date) {
      this.ctx.request.query.date = this.ctx.request.query.date.split('-');
      intYear = this.ctx.helper.checkInt(this.ctx.request.query.date[0]);
      intMonth = this.ctx.helper.checkInt(this.ctx.request.query.date[1]);
      intDay = this.ctx.helper.checkInt(this.ctx.request.query.date[2]);
      if (intYear > 0) {
        // Re-generate Calendar
        this.ctx.app.theCache.calendarHTML = await this.ctx.app.theCache.generateCalendar(intYear, intMonth);

        strURLPrefix += strURLPrefix == '?' ? '' : '&amp;';

        strURLPrefix += 'date=' + intYear;
        sqlWHERE += ' AND Year(log_postTime)=' + intYear;
        if (intMonth > 0 && intMonth < 13) {
          strURLPrefix += '-' + intMonth;
          sqlWHERE += ' AND Month(log_postTime)=' + intMonth;
          if (intDay > 0 && intDay < 32) {
            strURLPrefix += '-' + intDay;
            sqlWHERE += ' AND Day(log_postTime)=' + intDay;
          }
        }
      }
    }

    // Check for Hidden category display rights
    if (this.ctx.theUser.rights.view < 2) {
      for (let i = 0; i < this.ctx.app.theCache.categories.length; i++) {
        if (this.ctx.app.theCache.categories[i].hidden) {
          sqlWHERE += ' AND log_catid<>' + this.ctx.app.theCache.categories[i].id;
        }
      }
    }

    // Load articles from DB when needed
    let articles;
    let entryCount;
    const entryPerPage = (viewMode == 1 ? this.ctx.app.theCache.settings.articlePerPageList : this.ctx.app.theCache.settings.articlePerPageNormal);
    if (this.ctx.request.query.page > 1 || this.ctx.request.query.cat > 0 || this.ctx.request.query.user > 0 || this.ctx.request.query.selected == 'true' || this.ctx.request.query.q || intYear > 0 || viewMode == 1) {
      let strSQL = 'SELECT ';

      if (viewMode == 1) {
        strSQL += 'log_id, log_catID, log_title, log_authorID, log_author, log_mode, log_ubbFlags, log_postTime, log_ip, log_locked, log_selected, log_commentCount, log_viewCount, log_trackbackCount';
      } else {
        strSQL += 'log_id, log_catID, log_title, log_content0, Left(log_content1,2) as log_content1, log_authorID, log_author, log_mode, log_ubbFlags, log_postTime, log_ip, log_locked, log_selected, log_commentCount, log_viewCount, log_trackbackCount';
      }
      strSQL += ' FROM blog_article' + sqlWHERE + ' ORDER BY log_postTime DESC';

      articles = await this.ctx.app.connBlog.query(strSQL, entryPerPage, this.ctx.request.query.page, false);

      if (articles) {
        entryCount = this.ctx.app.connBlog.recordCount;
      } else {
        articles = [];
        entryCount = 0;
      }
    } else {
      articles = this.ctx.app.theCache.recentArticles;
      entryCount = this.ctx.app.theCache.settings.counterArticle;

      if (this.ctx.theUser.rights.view < 2) {
        for (let i = 0; i < this.ctx.app.theCache.categories.length; i++) {
          if (this.ctx.app.theCache.categories[i].hidden) {
            entryCount = entryCount - this.ctx.app.theCache.categories[i].articleCount;
          }
        }
      }
    }

    // Generate a security code for reference
    this.ctx.genSecurityCode();

    const arrArticle = [];
    const tArticle = this.ctx.service.article;
    for (let i = 0; i < articles.length; i++) {

      await tArticle.fill(articles[i]);

      arrArticle.push(Object.assign({}, tArticle));
    }

    const data = {
      viewMode,
      arrArticle,
      intEntryCount: entryCount,
      intEntryPerPage: entryPerPage,
      intCurrentPage: this.ctx.request.query.page,
      intCategory: this.ctx.request.query.cat,
      strURLPrefix,
      arrKeywords,
      intYear: '2017',
      intMonth: '12',
      input: this.ctx.request.query,
    };

    await this.ctx.render('default/default.ejs', data);
  }

  async about() {
    this.ctx.locals.strTitle = 'About';

    await this.ctx.render('about/about.ejs');
  }
}

module.exports = HomeController;
